<?php

namespace XWAM\Model;

/**
 * Description of UserModel
 *
 * @author Su 2016-2-1
 */
class UserSeatModel extends AppbaseModel {

    protected $tableName = 't_porg_user';
    protected $patchValidate = true;

    /**
     * 获取来电弹屏模式
     * @param type $uid
     * @return type
     * @since 1.0 <2016-3-12> SoChishun Added.
     */
    public function get_screenpopup_mode($uid, $site_conf) {
        $cache_name = 'screenpopup_mode_' . $uid;
        $sval = S($cache_name);
        if ($sval) {
            return $sval;
        }
        $sval = $this->table('t_porg_user_cti')->where(array('user_id' => $uid))->getField('screenpopup_mode');
        if (!$sval && $site_conf) {
            $sval = $site_conf['cti_screenpop_mode'];
        }
        S($cache_name, $sval, 5);
        return $sval;
    }

    /**
     * 修改密码
     * @param string|array $where 查询条件
     * @param string $pwd 新密码
     * @return false|int 成功则返回受影响数量,失败返回false
     * @since 1.0 2015-3-6 by sutroon
     */
    public function update_password($where, $pwd) {
        $result = $M->where($where)->setField('password', $pwd);
        $condition = is_array($where) ? sofunc_array_implode(',', $where) : $where;
        $log = new LogModel();
        $log->log_user_operate(false !== $result, "[修改密码%] $condition, password=$pwd", 0, LogModel::ACTION_EDIT);
        return $result;
    }

    /**
     * 获取坐席
     * @param type $id
     * @return type
     * @since 1.0 2016-2-2 SoChishun Added.
     */
    function find_seat($id) {
        $data = $this->find($id);
        if ($data) {
            $cti = $this->table('t_porg_user_cti')->field('screenpopup_mode,trunk,queue,caller_no')->where(array('user_id' => $id))->find();
            if ($cti) {
                $data = array_merge($data, $cti);
            } else {
                $this->table('t_porg_user_cti')->add(array('user_id' => $data['id'], 'extension' => $data['user_name']));
            }
        }
        return $data;
    }

    /**
     * 保存用户
     * @param int $admin_id 用户编号
     * @return array
     * @since 1.0 2015-3-6 by sutroon
     */
    public function save_user($admin_id) {
        $validator = array(
            array('user_name', 'require', '用户名无效!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
            array('user_name', 'check_user_name', '用户名已被注册!', self::MUST_VALIDATE, 'callback', self::MODEL_INSERT),
            array('password', 'require', '密码无效!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
            array('status', 'number', '状态有误!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        );
        if (!$this->validate($validator)->create()) {
            return $this->returnMsg(false, $this->getError());
        }
        //图片上传
        $msg = \Common\Controller\UploadHandlerController::upload(array('savePath' => 'Face/', 'skipEmpty' => true, 'exts' => array('jpg', 'jpeg', 'png', 'gif')));
        if (is_array($msg)) {
            $this->data['face_url'] = $msg['face_url']['filepath'];
        }
        $data = $this->data;
        unset($this->data['screenpopup_mode']);
        if (empty($this->id)) {
            $this->type_name = 'SEAT';
            unset($this->data['id']);
            $result = $this->add();
            if (false !== $result) {
                // 添加到cti表
                $this->table('t_porg_user_cti')->add(array('user_id' => $result, 'screenpopup_mode' => $data['screenpopup_mode']));
            }
        } else {
            $result = $this->save();
            if (false !== $result) {
                // 更新到cti表
                $this->table('t_porg_user_cti')->where(array('user_id' => $data['id']))->setField(array('screenpopup_mode' => $data['screenpopup_mode']));
            }
        }
        return $this->returnMsg($result);
    }

    // 检测用户名是否重复 2016-4-8 SoChishun Added.
    function check_user_name($val) {
        $n = $this->where(array('user_name' => trim($val)))->count('id');
        return $n < 1;
    }

    /**
     * 删除用户
     * @param string $id 主键编号,多个之间以逗号隔开
     * @param int $admin_id 操作员编号
     * @return array
     * @since 1.0 <2015-6-10> SoChishun Added.
     */
    public function delete_user($id, $admin_id) {
        if (!$admin_id) {
            return $this->returnMsg(false, '用户无效');
        }
        if (!$id) {
            return $this->returnMsg(false, '编号无效');
        }
        $result = $this->delete($id);
        $log = new LogModel();
        $log->log_user_operate($status, "删除用户账户($id){%} $msg,操作员:$admin_id", $admin_id, LogModel::ACTION_DELETE);
        return $this->returnMsg($result);
    }

    /**
     * 从XCall同步分机到坐席
     * @since 1.0 <2016-2-15> SoChishun Added.
     */
    public function user_from_xcall($site_id) {
        $extens = $this->table('db_xcall.tuser_member')->where(array('siteID' => $site_id, 'userType' => 'SEAT'))->getField('userName', true);
        $seats = $this->cache(false)->where(array('type_name' => 'SEAT'))->getField('user_name', true);
        if (!$extens) {
            return 0;
        }
        $diff = $seats ? array_diff($extens, $seats) : $extens;
        if ($diff) {
            $sql = 'insert into t_porg_user (user_name, type_name, password, status, role_ids, site_id) values ';
            $sqls = array();
            foreach ($diff as $name) {
                $sqls[] = "('$name','SEAT','123456',1, 3, $site_id)";
            }
            $result = $this->execute($sql . implode(',', $sqls));
        }
        return count($diff);
    }

}
